package com.os.advice;

import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Author Matt
 * @Date 2022-01-16
 * @Desc:
 * @Version V1.0
 */
@ControllerAdvice  //声明一个控制器建言 组合了@component注解，所以会自动注册为spring的bean
public class ExceptionHandlerAdvice {

    //在此处定义全局异常处理，value我们设置拦截所有异常
    @ExceptionHandler(value = Exception.class)
    public ModelAndView exception(Exception exception, WebRequest request){
        ModelAndView modelAndView = new ModelAndView("error");  //error页面
        modelAndView.addObject("errorMessage", exception.getMessage());
        return modelAndView;
    }

    //此处将键值对添加到全局，所有注解@requestmapping的方法将获得此键值对
    @ModelAttribute
    public void addAttributes(Model model){
        model.addAttribute("msg", "额外信息");
    }

    //定制webDataBinder
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder){
        webDataBinder.setDisallowedFields("id");
    }
}
